<%@ page pageEncoding="UTF-8"%>
<%@ include file="/common/token.jsp"%>
<%@ include file="/common/task.jsp"%>
<%@ include file="/common/user.jsp"%>
<%
    String uids = input.getDesc("uids", "");
    Integer groupId = input.getInt("group_id", -1);
    String[] _uids = uids.split("\\|");
    if (groupId < 0) {
        msg = new Message(30062, "请选择分组");
        Tools.encryptPrint(out, msg);
        return;
    }
    if ("".equals(uids) || isEmpty(_uids)) {
        msg = new Message(30062, "请选择要加入的用户");
        Tools.encryptPrint(out, msg);
        return;
    }
    MyTask task = new MyTask(_uids.length);
    for (int i = 0; i < _uids.length; i++) {
        GroupPatient groupPatient = new GroupPatient();
        groupPatient.setHospital(hospital);
        groupPatient.setGroupId(groupId);
        task.runTask(task.new MyRunnable(task.new DBOperate() {

				@Override
				public Object operate(Object... objects) {
                    List<Integer> userIds = new ArrayList<Integer>();
                    Integer patientUid = Tools.getInt(objects[0]+"", 0);
                    userIds.add(patientUid);
                    Map<Integer, User> users = usersByUids(userIds);
                    User user = users.get(patientUid);

					GroupPatient groupPatient = (GroupPatient)objects[1];
                    groupPatient.setPatientUid(patientUid);
                    List<GroupPatient> groupPatients = QBuilder.db("basedb").select().from("GroupPatient").where(new Where("groupId=", groupPatient.getGroupId()).and("status = ", STATUS_ENABLE).and("hospital =", groupPatient.getHospital()).and("patientUid=", patientUid)).query().getResultObj();
                    if (!isEmpty(groupPatients)) {
                        if (user != null) {
                            return user.getName();
                        }
                    }
                    Integer groupPatientId = (Integer)DBTools.db("basedb").addItem(groupPatient);
                    if (isEmpty(groupPatientId)) {
                        if (user != null) {
                            return user.getName();
                        }
                    }
					return null;
				}
			}, i, new Object[]{_uids[i], groupPatient}));
    }
    task.stopTask();
    Object[] results = task.getResult();
    String names = "";
    for (int i = 0; i < results.length; i++) {
        Object obj = results[i];
        if (!isEmpty(obj)) {
            names += obj + ",";
        }
    }
    if (!"".equals(names)) {
        names = names.substring(0, names.length() - 1) + "添加失败或已经存在";
    }
    msg.put("data", names);
    Tools.encryptPrint(out, msg);
%>
